package com.bawei.play

import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.aspectj.CheckLoginState
import com.bawei.base.RoutePath
import com.bawei.common.entity.SimpleVideoEntity
import com.bawei.common.mvi.BaseMviActivity
import com.bawei.common.view.SnapPageLayoutManager
import com.bawei.play.adapter.PlayVideoAdapter
import com.bawei.play.databinding.ActivityPlayBinding
import com.bawei.play.intent.PlayViewIntent
import com.bawei.play.state.PlayUiState
import com.bawei.play.vm.PlayViewModel
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.tencent.mmkv.MMKV
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = RoutePath.PATH_PLAY_PAGE)
@AndroidEntryPoint
class PlayActivity : BaseMviActivity<ActivityPlayBinding>() {

    @Autowired
    lateinit var videoEntity: SimpleVideoEntity

    @Autowired
    @JvmField
    var typeId: Int = -1

    @Autowired
    @JvmField
    var channelId: String = ""

    private val mViewModel: PlayViewModel by viewModels()
    private var videoList = mutableListOf<SimpleVideoEntity>()
    private lateinit var snapPageLayoutManager: SnapPageLayoutManager
    private lateinit var mVideoAdapter: PlayVideoAdapter
    private var mVideoPlayer : StandardGSYVideoPlayer? = null

    private var mCurrentPageIndex: Int = 0
    private var pageIndex = 1
    private var pageSize = 10

    override fun getLayoutId(): Int = R.layout.activity_play

    override fun initViews() {
        ARouter.getInstance().inject(this)
        //把传递进来的数据当成第一条数据
        videoEntity?.let { videoList.add(it) }
        //下拉刷新和加载更多事件监听
        mDataBinding.smartRefresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener{
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                loadMoreOrRefresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                pageIndex += 1
                loadMoreOrRefresh()
            }
        })

        //设置布局布局管理器
        snapPageLayoutManager = SnapPageLayoutManager(this@PlayActivity)
        mDataBinding.rvVideo.layoutManager = snapPageLayoutManager
        mVideoAdapter = PlayVideoAdapter(videoList)

        //设置子组件点击事件
        mVideoAdapter.setOnItemClickListener(object : PlayVideoAdapter.OnItemChildClickListener{
            override fun onItemChildClick(v: View, position: Int) {
                when(v.id){
                    R.id.iv_head -> {
                        jumpUserMainPage()
                    }
                    R.id.iv_add ->{
                        addUserFouce()
                    }
                    R.id.iv_dian_zan_btn ->{
                        userDianZan()
                    }
                    R.id.iv_ping_lun_btn -> {
                        videoPingLun()
                    }
                    R.id.iv_shou_cang_btn ->{
                        videoShouCang()
                    }
                    R.id.iv_share_btn -> {
                        videoShare()
                    }
                }
            }
        })

        //添加列表滚动事件
        mDataBinding.rvVideo.addOnScrollListener(object: RecyclerView.OnScrollListener(){
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                mCurrentPageIndex = snapPageLayoutManager.findFirstVisibleItemPosition()
                videoEntity = videoList[mCurrentPageIndex]
                //获取当期Item布局中的GSY播放器
                mVideoPlayer = (mDataBinding.rvVideo.findViewHolderForLayoutPosition(mCurrentPageIndex) as PlayVideoAdapter.VideoPlayViewHolder).dataBinding.gsyPlayer
                //播放视频
                mVideoPlayer?.isLooping = true //是否循环播放
                mVideoPlayer?.startPlayLogic()

            }


            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                //滑动时候要释放上一个播放器
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING){
                    mVideoPlayer?.release()
                }
            }

        })

        //局部更新UI
        mDataBinding.rvVideo.swapAdapter(mVideoAdapter, true)

    }

    /**
     * 视频分享
     */
    @CheckLoginState
    private fun videoShare() {
        var userToken = MMKV.defaultMMKV().decodeString("token", "")
        if (!userToken.isNullOrEmpty()){
            //调用接口
        }else{
            ARouter.getInstance().build(RoutePath.PATH_LOGIN_PAGE).navigation()
        }
    }

    /**
     * 视频收藏
     */
    @CheckLoginState
    private fun videoShouCang() {
        var userToken = MMKV.defaultMMKV().decodeString("token", "")
        if (!userToken.isNullOrEmpty()){
            //调用接口
        }else{
            ARouter.getInstance().build(RoutePath.PATH_LOGIN_PAGE).navigation()
        }

    }

    /**
     * 视频评论
     */
    @CheckLoginState
    private fun videoPingLun() {
        var userToken = MMKV.defaultMMKV().decodeString("token", "")
        if (!userToken.isNullOrEmpty()){
            //调用接口
        }else{
            ARouter.getInstance().build(RoutePath.PATH_LOGIN_PAGE).navigation()
        }

    }

    /**
     * 视频点赞
     */
    @CheckLoginState
    private fun userDianZan() {
        var userToken = MMKV.defaultMMKV().decodeString("token", "")
        if (!userToken.isNullOrEmpty()){
            //调用接口
        }else{
            ARouter.getInstance().build(RoutePath.PATH_LOGIN_PAGE).navigation()
        }

    }

    /**
     * 关注用户
     */
    @CheckLoginState
    private fun addUserFouce() {
        var userToken = MMKV.defaultMMKV().decodeString("token", "")
        if (!userToken.isNullOrEmpty()){
            //调用接口
        }else{
            ARouter.getInstance().build(RoutePath.PATH_LOGIN_PAGE).navigation()
        }

    }

    /**
     * 进入用户主页
     */
    @CheckLoginState
    private fun jumpUserMainPage() {
        var userToken = MMKV.defaultMMKV().decodeString("token", "")
        if (!userToken.isNullOrEmpty()){
            //调用接口
        }else{
            ARouter.getInstance().build(RoutePath.PATH_LOGIN_PAGE).navigation()
        }

    }


    private fun loadMoreOrRefresh(){
        lifecycleScope.launch {
            if(typeId == -1){
                mViewModel.channel.send(PlayViewIntent.LoadRecommendSimpleVideoList(pageIndex, pageSize))
            }else{
                mViewModel.channel.send(PlayViewIntent.LoadSimpleVideoListById(channelId, pageIndex, pageSize))
            }
        }
    }

    override suspend fun sendViewIntent() {
        if(typeId == -1){
            mViewModel.channel.send(PlayViewIntent.LoadRecommendSimpleVideoList(pageIndex, pageSize))
        }else{
            mViewModel.channel.send(PlayViewIntent.LoadSimpleVideoListById(channelId, pageIndex, pageSize))
        }
    }

    override suspend fun collectUiState() {
        mViewModel.uiState.collect{
            when(it){
                is PlayUiState.LoadSimpleVideoSuccess -> {
                    Log.i("======", "collectUiState=====>>>>: ${it?.list?.size}")
                    //停止下拉刷新
                    mDataBinding.smartRefresh.finishRefresh()
                    var oldListSize = videoList.size
                    //下拉刷新时，数据大于1，才清理数据，并做整体刷新
                    if (pageIndex == 1 && oldListSize > 1){
                        videoList.clear()
                        videoList.addAll(it.list)
                        mVideoAdapter.notifyDataSetChanged() //全部刷新
                    } else {
                        //过滤一下数据，因为第一条数据是传递进来
                        videoList.addAll(it.list.filter { entity -> entity.id != videoEntity.id })
                        var startPosition = if (oldListSize > 1) oldListSize - 1 else 1
                        //指定刷新的范围，执行局部刷新，可以避免当前视频重新播放
                        mVideoAdapter.notifyItemRangeChanged(startPosition, videoList.size - 1)
                    }
                }
                is PlayUiState.LoadSimpleVideoFail -> {
                    showToastMsg(it.msg)
                }
                else -> {}
            }
        }
    }

    override fun onResume() {
        mVideoPlayer?.onVideoResume()
        super.onResume()
    }

    override fun onPause() {
        mVideoPlayer?.onVideoPause()
        super.onPause()
    }

    override fun onDestroy() {
        mVideoPlayer?.release()
        mVideoPlayer = null //方便GC回收
        super.onDestroy()
    }


}